package com.example.meituan.activity.man.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.meituan.R;
import java.util.ArrayList;
import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {

    private final Context context;
    private final List<String> images; // 假设存储的是图片路径或URL
    private final OnItemClickListener listener;

    public interface OnItemClickListener {
        void onRemoveClick(int position);
    }

    public ImageAdapter(Context context, List<String> images, OnItemClickListener listener) {
        this.context = context;
        this.images = new ArrayList<>(images);
        this.listener = listener;
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image, parent, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        String imagePath = images.get(position);
        Glide.with(context)
                .load(imagePath) // 加载本地文件路径或网络URL
                .placeholder(R.drawable.photo) // 设置占位符
                .error(R.drawable.logo) // 设置错误占位符
                .into(holder.imageView);
        holder.closeButton.setOnClickListener(v -> {
            // 移除图片并更新适配器
            images.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, getItemCount() - position); // 更新剩余项
        });
    }

    @Override
    public int getItemCount() {
        return images.size();
    }

    public void addImage(String path) {
        int position = images.size();
        images.add(path);
        notifyItemInserted(position);
    }

    public void removeImage(int position) {
        if (position >= 0 && position < images.size()) {
            images.remove(position);
            notifyItemRemoved(position);
        }
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageButton closeButton;

        ImageViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            closeButton = itemView.findViewById(R.id.closeButton);
        }
    }
}
